﻿#include <mosquitto.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

int main(void)
{
	struct mosquitto *mosq;
	int rc;
	//初始化mosquitto库
	mosquitto_lib_init();
	
	//创建客户端对象
	mosq = mosquitto_new(NULL, true, NULL);
	if(mosq == NULL){
		fprintf(stderr, "Error: Out of memory.\n");
		return -1;
	}
	
	//连接MQTT服务器
	rc = mosquitto_connect(mosq, "8.137.86.5", 1883, 60);
	if(rc != MOSQ_ERR_SUCCESS){
		mosquitto_destroy(mosq);
		fprintf(stderr, "Error: %s\n", mosquitto_strerror(rc));
		return -1;
	}
	printf("连接MQTT服务器成功\n");
	
	//进入事件循环
	rc = mosquitto_loop_start(mosq);
	if(rc != MOSQ_ERR_SUCCESS){
		mosquitto_destroy(mosq);
		fprintf(stderr, "Error: %s\n", mosquitto_strerror(rc));
		return 1;
	}
	int num;
	char payload[100];
	while(1)
	{
		bzero(payload,sizeof(payload));
		
		//生成一个随机数
		num = random()%100;
		sprintf(payload,"temp:%d\n",num);
		
		//发布主题
		rc = mosquitto_publish(mosq, NULL, "aaaa", strlen(payload), payload, 0, false);
		if(rc != MOSQ_ERR_SUCCESS)
		{
			fprintf(stderr, "Error publishing: %s\n", mosquitto_strerror(rc));
		}
		
		sleep(1); 
	}
	
}

